/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package fr.jade.fraclite.orb;

import java.lang.reflect.Proxy;
import java.util.Map;

import org.objectweb.fractal.api.Interface;

import fr.jade.fraclite.api.ComponentInterface;
import fr.jade.fraclite.orb.common.api.Binder;
import fr.jade.fraclite.orb.common.api.Name;
import fr.jade.fraclite.orb.common.api.NamingException;
import fr.jade.fraclite.orb.common.api.RemoteReference;
import fr.jade.fraclite.orb.common.api.Skeleton;
import fr.jade.fraclite.orb.common.api.StubFactory;

/**
 * 
 * @author Sylvain Sicard
 *
 */
public class MulticastStubFactory implements StubFactory {
	
	protected ClassLoader cl = null;
	protected Skeleton s = null;
  //protected ExecutorService es;
  protected Long stubId = 0L;
  
	public MulticastStubFactory(ClassLoader cl){
	  this.cl = cl;
	  stubId = Long.parseLong(System.getProperty("fraclite.ha.vmid"))*100000;
	}

  public Object newStub(Binder binder, Name name) throws NamingException{
    Long id = stubId++;
    //System.out.println("New stub("+id+") for name "+name);
    MulticastStub stub = new MulticastStub(name, id);
    try {
      String signature = name.getSignature();
      Class<?> itf = cl.loadClass(signature);
      Class<?>[] itfs = new Class[]{itf, ComponentInterface.class, RemoteReference.class};
      return Proxy.newProxyInstance(cl, itfs, stub);
    } catch (ClassNotFoundException e) {
      throw new NamingException("Cannot create stub "+e.toString() );
    }
  }
  
  public Object newSkeleton(Map<String,?> hints, Object target, Binder naming) throws NamingException{
    s = new MulticastSkeleton(naming);
    s.registerTarget(target);
    //System.out.println("new skeleton for itf "+((Interface)target).getFcItfGUId());
    return s;
  }

  
  
}
